local FieldType = {
	int = 1,
	string = 2,
};


local function readint(data, start_pos)
	return bin.to_int(string.sub(data, start_pos, start_pos+3));
end

local function read_message(data, msg_config)
	local cur_read_pos = 1;
	if(cur_read_pos + 3 > string.len(data)) then return nil; end
	local total_len = readint(data, cur_read_pos);
	cur_read_pos = cur_read_pos + 4;

	local ret = {};
	for k, v in ipairs(msg_config) do
		local key = v.key and v.key or k;
		local msg_type = v.type;
		if msg_type  == FieldType.string then
			if(cur_read_pos + 3 > string.len(data)) then
				return nil;
			end
			local len = readint(data, cur_read_pos);
			cur_read_pos = cur_read_pos + 4;

			if(cur_read_pos + len - 1 > string.len(data)) then
				return nil;
			end
			local msg = string.sub(data, cur_read_pos,
					cur_read_pos + len - 1);
			ret[key] = msg;
			cur_read_pos = cur_read_pos + len;
		elseif msg_type == FieldType.int then
			ret[key] = readint(data, cur_read_pos);
			cur_read_pos = cur_read_pos + 4;
		end
	end
	return ret;
end

local MessageDef = {
	ping = {
		{key = "message", type = FieldType.string},
	},

	login = {
		{key = "type", type = FieldType.int},
		{key = "user",  type = FieldType.string},
	},
};

local function getMessageType(data)
	if (string.len(data) < 8) then
		return nil;	
	end

	return bin.to_int(data, 5, 8);
end

function process(conn, data)
--[[
	local msgType = getMessageType(data);
	local msg = nil;
	if (msgType == 1) then
		msg = read_message(data, MessageDef.ping);
	end

	if (msgType == 2) then
		msg = read_message(data, MessageDef.login);
	end
--]]
	local msg = read_message(data, MessageDef.ping)
	local str = msg.message .. " : answer";

	msg_len = string.len(str);
	total_len = msg_len + 4;

	connection.write(conn, bin.from_int(total_len));
	connection.write(conn, bin.from_int(msg_len));
	connection.write(conn, str);
	--connection.close(conn);
end
